<template>
  <div class="text-[12px] w-full user-select">
    <div class="w-full schedule">
      <div class="w-full flex bg-[#F2F2F2] header">
        <div class="w-[70px] flex justify-center items-center shrink-0 cursor-pointer cols" @click.stop="selectAll">星期/时间</div>
        <div class="col">
          <div class="flex justify-center cursor-pointer items-center py-[4px] time" @click.stop="selectHalfDay(0)">00:00-12:00</div>
          <div class="flex timesub">
            <div
              class="flex justify-center items-center cursor-pointer py-[4px] sub lastSub"
              v-for="item in 12"
              :key="item"
              @click.stop="selectHours(item - 1)"
            >
              {{ item - 1 }}
            </div>
          </div>
        </div>
        <div class="col">
          <div class="flex justify-center cursor-pointer items-center py-[4px] time" @click.stop="selectHalfDay(1)">12:00-24:00</div>
          <div class="flex timesub">
            <div
              class="flex justify-center items-center cursor-pointer py-[4px] sub"
              v-for="item in 12"
              :key="item"
              @click.stop="selectHours(item + 11)"
            >
              {{ item + 11 }}
            </div>
          </div>
        </div>
      </div>
      <div class="w-full flex row" v-for="(day, index) in days" :key="day">
        <div class="w-[70px] flex justify-center items-center py-[4px] bg-[#F2F2F2] cursor-pointer shrink-0 col" @click.stop="selectDay(index)">
          {{ day }}
        </div>
        <div
          class="w-full flex items-center cursor-pointer justify-center time"
          v-for="(subItem, subIndex) in daysTime[index]"
          :key="subIndex"
          :class="subItem === 1 ? 'active' : ''"
          @click.stop="toggleTimeSlot(index, subIndex)"
        ></div>
      </div>
    </div>
    <div class="selected-times">
      <h4>选中的时间段:</h4>
      <div v-for="(timeRange, index) in days" :key="index">
        <div class="flex items-baseline res" v-if="selectDayRes[index]">
          <div class="label">{{ timeRange }}：</div>
          <div class="text-[#999] value">{{ selectDayRes[index] }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

const emit = defineEmits(['getValue']);

const props = defineProps({
  needSelectText: {
    type: Boolean,
    default: false
  }
});

const timeSlots = Array(48).fill(0); // 初始化为 0
const days = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];

// 使用 Array.from 生成包含 7 个数组的 daysTime，每个数组都是 timeSlots 的副本
const daysTime = ref(Array.from({ length: days.length }, () => [...timeSlots]));

const selectDayRes = ref(Array.from({ length: days.length }, () => null));

/**
 * 选择全部
 */
const selectAll = () => {
  daysTime.value.forEach((day) => {
    day.fill(day[0] === 0 ? 1 : 0); // 反转当前选择状态
  });
};

/**
 * 选择一天
 */
const selectDay = (dayIndex: number) => {
  daysTime.value[dayIndex].forEach((_, index) => {
    daysTime.value[dayIndex][index] = daysTime.value[dayIndex][index] === 0 ? 1 : 0; // 切换选择状态
  });
};

/**
 * 选择半天
 */
const selectHalfDay = (half: number) => {
  const startNum = half === 0 ? 0 : 24;
  const endNum = half === 0 ? 23 : 47;

  daysTime.value.forEach((day) => {
    for (let i = startNum; i <= endNum; i++) {
      day[i] = day[i] === 0 ? 1 : 0; // 切换选择状态
    }
  });
};

/**
 * 选择小时
 */
const selectHours = (hour: number) => {
  const slotsToToggle = [2 * hour, 2 * hour + 1]; // 每小时对应两个时间段
  daysTime.value.forEach((day) => {
    slotsToToggle.forEach((slot) => {
      day[slot] = day[slot] === 0 ? 1 : 0; // 切换选择状态
    });
  });
};

/**
 * 切换时间段选择
 */
const toggleTimeSlot = (dayIndex: number, slotIndex: number) => {
  daysTime.value[dayIndex][slotIndex] = daysTime.value[dayIndex][slotIndex] === 0 ? 1 : 0; // 切换选择状态
};

/**
 * 获取选中时间段
 */
const getSelectedTimeRanges = (dayIndex: number) => {
  const selectedRanges = [];
  const slots = daysTime.value[dayIndex];

  if (!slots) return selectedRanges; // 添加检查，防止 undefined 错误

  let start = null;
  let end = null;

  for (let i = 0; i < slots.length; i++) {
    if (slots[i] === 1) {
      // 当前时间段被选中
      if (start === null) {
        start = i; // 开始新的时间段
      }
      end = i; // 更新结束时间
    } else {
      // 当前时间段未选中
      if (start !== null) {
        const startTime = formatTime(start, 'start');
        const endTime = formatTime(end, 'end');
        selectedRanges.push(`${startTime}-${endTime}`);
        start = null; // 重置开始
        end = null; // 重置结束
      }
    }
  }
  // 如果最后一段是选中的，处理它
  if (start !== null) {
    const startTime = formatTime(start, 'start');
    const endTime = formatTime(end, 'end');
    selectedRanges.push(`${startTime}-${endTime}`);
  }

  return selectedRanges.join(', '); // 用逗号分隔多个时间段
};

/**
 * 格式化时间
 */
const formatTime = (slot: number, type: 'start' | 'end') => {
  const hour = Math.floor(slot / 2);
  const isEven = slot % 2 === 0;

  const formattedHour = type === 'end' && !isEven ? hour + 1 : hour;
  const minute = type === 'start' ? (isEven ? '00' : '30') : isEven ? '30' : '00';

  return `${formattedHour.toString().padStart(2, '0')}:${minute}`;
};

const getValue = (items) => {
  let str = '';
  items.map((item) => {
    item.map((subitem) => {
      str += subitem;
    });
  });
  if (!props.needSelectText) {
    emit('getValue', str);
  } else {
    let timestr = '';
    selectDayRes.value.map((subitem, subindex) => {
      if (subitem) {
        timestr += days[subindex] + ': ' + subitem + '; ';
      }
    });
    emit('getValue', { str, days: timestr });
  }
};

watch(
  daysTime,
  (newValue) => {
    newValue.forEach((slots, index) => {
      const selectedRanges = getSelectedTimeRanges(index);
      selectDayRes.value[index] = selectedRanges;
    });
    getValue(newValue);
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.header {
  .cols {
    border: 1px solid #ccc;
    border-right: 0;
  }
  .col {
    width: calc((100% - 70px) * 0.5);
    .time {
      border: 1px solid #ccc;
      border-bottom: 0;
      border-right: 0;
    }
    &:last-child {
      .time {
        border-right: 1px solid #ccc;
      }
    }
    .timesub {
      .sub {
        flex: 0 0 8.33333333333333%;
        border: 1px solid #ccc;
        border-right: 0;
        &:last-child {
          border-right: 1px solid #ccc;
        }
      }
    }
  }
}
.row {
  .col {
    border: 1px solid #ccc;
    &:first-child {
      border-top: 0;
    }
    &:last-child {
      border-bottom: 1px solid #ccc;
    }
  }
  .time {
    width: calc(100% - 70px);
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    &.active {
      background-color: #0057ff;
    }
  }
}
.selected-times {
  margin-top: 10px;
}
</style>
